﻿using CarAppClient.Consts;
using CarAppClient.Controls.MessageUsercontrols;
using CarAppClient.Extension;
using CarAppClient.Helpers;
using CarAppClient.ViewModels;
using D.UtilCore.Dtos;
using System.Collections.ObjectModel;
using DelegateCommand = D.WPF.MVVM.EventUtil.DelegateCommand;
using CarAppClient.Views.CarParts.ViewModels.CarParts;
using CarAppDto.CarParts.CarPartsDtos;
using SqlSugar;
using CarAppClient.Views.CarParts;
using System.Linq;
using CarAppClient.Views.Rule.Views;
using CarAppClient.Views.CarType.Views.Brand;
using CarAppClient.Views.CarType.ViewModels.CarType;
using CarAppDto.CarType.BrandDtos;
using CarAppDto.Rule.RuleMappingDtos;
using CarAppDto.CarType.CarTypeDtos;
using CarAppDto.CarType.AreaDtos;
using CarAppDto.CarType.CountryDtos;
using CarAppDto.CarType.VehicleSeriesDtos;
using CarAppDto.Rule.RuleConfigDtos;
using System.Windows;
using CarAppClient.Views.RuleConfig.ViewModels.RuleConfig;
using CarAppClient.Views.CarType.Views.CarType;
using CarAppClient.Views.CarType.Views.VehicleSeries;
using CarAppClient.Views.CarType.Views.CarTypeVersion;
using CarAppDto.CarType.CarTypeVersionDtos;
using CarAppClient.Views.CarTypeVersion.ViewModels.CarTypeVersion;
using System.Data;
using Newtonsoft.Json.Linq;
using System.Windows.Media;
using System.Windows.Input;
using CarAppDto.Common;

namespace CarAppClient.Views.RuleMapping.ViewModels.RuleMapping
{
    public class RuleMappingModifyViewModel : BaseModifyViewModel<Page_RuleMapping_Modify>
    {
        #region 加载页面数据
        string _ruleId;
        public RuleMappingModifyViewModel(Page_RuleMapping_Modify owner, string? id, string? ruleId, ViewStatus? viewStatus) : base(owner, id, viewStatus)
        {
            _ruleId = ruleId;
        }

        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="repRuleMapping"></param>
        protected async override void LoadData()
        {
            string[] values = Enum.GetNames(typeof(MappingDetailsDisplayType));
            MappingDetailsDisplayTypeList.AddRange(values);
            if (!string.IsNullOrEmpty(Id))
            {
                // 请求后端接口 
                var res = await HttpHelper<RepRuleMapping>.GetAsync($"{ApiUrl.GetRuleMapping}/{Id}");

                //  判断结果
                if (res.Code == StatusCodeEnum.Waring)
                {
                    MsgUtil.Error(res.ErrorMsg);
                }
                else if (res.Code == StatusCodeEnum.Error)
                {
                    MsgUtil.Error("服务器异常");
                }
                else
                {
                    // 绑定数据源到UI 
                    if (res.Data != null)
                    {
                        Key = res.Data.Key;
                        Descption = res.Data.Descption; 
                        Val = res.Data.Val;
                        RegStr= res.Data.RegStr;
                        SelectedTypeIndex = (int)res.Data.Details.Type;
                        SelectedTypeChange(SelectedTypeIndex);

                        if (res.Data.Details.ValueDetailsList != null)
                        {
                            foreach (ValueDetails item in res.Data.Details.ValueDetailsList)
                            {
                                MappingDetails valueDetails = new MappingDetails();
                                valueDetails.Key = item.Key;
                                valueDetails.Value = item.Value;
                                MappingDetailsList.Add(valueDetails);
                            }
                        }
                        else if(res.Data.Details.ReferenceDetails!=null)
                        {
                            MappingDetails valueDetails = new MappingDetails();
                            valueDetails.Key = res.Data.Details.ReferenceDetails.Key;
                            valueDetails.Value = res.Data.Details.ReferenceDetails.Value;
                            valueDetails.Id= res.Data.Details.ReferenceDetails.Id;
                            MappingDetailsList.Add(valueDetails);
                        }
                    }
                }
            }
        }
        #endregion

        #region 操作按钮显示隐藏权限

        private Visibility addBtnVisibility = Visibility.Visible;
        /// <summary>
        /// 新增按钮状态
        /// </summary>
        public Visibility AddBtnVisibility
        {
            get { return addBtnVisibility; }
            set { addBtnVisibility = value; RaisePropertyChanged(); }
        }

        private Visibility deleteBtnVisibility = Visibility.Visible;
        /// <summary>
        /// 删除按钮状态
        /// </summary>
        public Visibility DeleteBtnVisibility
        {
            get { return deleteBtnVisibility; }
            set { deleteBtnVisibility = value; RaisePropertyChanged(); }
        }

        private Visibility selectBtnVisibility = Visibility.Hidden;
        /// <summary>
        /// 修改按钮状态
        /// </summary>
        public Visibility SelectBtnVisibility
        {
            get { return selectBtnVisibility; }
            set { selectBtnVisibility = value; RaisePropertyChanged(); }
        }

        #endregion

        #region 新增、修改 参数

        /// <summary>
        /// 匹配项
        /// </summary>
        public string key;
        public string? Key
        {
            get { return key; }
            set { key = value; RaisePropertyChanged(); }
        }

        /// <summary>
        /// 匹配值
        /// </summary>
        public string val;
        public string? Val
        {
            get { return val; }
            set { val = value; RaisePropertyChanged(); }
        }

        /// <summary>
        /// 正则匹配
        /// </summary>
        public string regStr;
        public string? RegStr
        {
            get { return regStr; }
            set { regStr = value; RaisePropertyChanged(); }
        }

        /// <summary>
        /// 描述
        /// </summary>
        public string descption;
        public string? Descption
        {
            get { return descption; }
            set { descption = value; RaisePropertyChanged(); }
        }



        ObservableCollection<string> mappingDetailsDisplayTypeList = new ObservableCollection<string>();
        public ObservableCollection<string> MappingDetailsDisplayTypeList
        {
            get { return mappingDetailsDisplayTypeList; }
            set { mappingDetailsDisplayTypeList = value; RaisePropertyChanged();}
        }


        private int? selectedTypeIndex = 0;
        /// <summary>
        /// 选择的车型类型
        /// </summary>
        public int? SelectedTypeIndex
        {
            get { return selectedTypeIndex; }
            set { selectedTypeIndex = value; RaisePropertyChanged(); SelectedTypeChange(value); }
        }

        /// <summary>
        /// 匹配值
        /// </summary>
        ObservableCollection<MappingDetails> mappingDetailsList = new ObservableCollection<MappingDetails>();
        public ObservableCollection<MappingDetails> MappingDetailsList
        {
            get { return mappingDetailsList; }
            set { mappingDetailsList = value; RaisePropertyChanged(); }
        }

        #endregion

        #region 保存事件
        /// <summary>
        /// 提交
        /// </summary>
        /// <param name="vm"></param>
        protected override async void Submit(object? obj)
        {
            if ((!string.IsNullOrWhiteSpace(Val) || !string.IsNullOrWhiteSpace(Key))
                && !string.IsNullOrWhiteSpace(RegStr))
            {
                MsgUtil.Warning("正则匹配不能和值匹配同时使用！");
                return;
            }


            if ((!string.IsNullOrWhiteSpace(Val) && string.IsNullOrWhiteSpace(Key))
                || (string.IsNullOrWhiteSpace(Val) && !string.IsNullOrWhiteSpace(Key)))
            {
                MsgUtil.ShowMsg(StatusCodeEnum.Waring, "", "匹配项和匹配值不能为空！");
                return;
            }

            if (SelectedTypeIndex == -1)
            {
                MsgUtil.ShowMsg(StatusCodeEnum.Waring, "", "类型必选！");
                return;
            }

            if (mappingDetailsList.Count == 0)
            {
                MsgUtil.ShowMsg(StatusCodeEnum.Waring, "", "详情列表必选有值！");
                return;
            }

            RuleMappingValue keyValue=null;//判断是否是值匹配
            if (!string.IsNullOrWhiteSpace(Val) || !string.IsNullOrWhiteSpace(Key))
            {
                keyValue = new RuleMappingValue();
                keyValue.Key = Key;
                keyValue.Value = Val;
            }
            RuleMappingDetails details=new RuleMappingDetails();
            List<ValueDetails> valueDetails = new List<ValueDetails>();
            ReferenceDetails referenceDetails = new ReferenceDetails();
            RuleMappingDetails ruleMappingDetails = new RuleMappingDetails();
            ruleMappingDetails.Type =(MappingDetailsType)Enum.ToObject(typeof(MappingDetailsType), SelectedTypeIndex);
            if (SelectedTypeIndex == 0)
            {
                details.Type = MappingDetailsType.Value;
                 int i = 0;
                foreach (var item in MappingDetailsList)
                {
                    ValueDetails valueD = new ValueDetails();
                    valueD.Key = item.Key;
                    valueD.Value = item.Value;
                    valueD.Index = i;
                    valueDetails.Add(valueD);
                }
                ruleMappingDetails.ValueDetailsList=valueDetails;
            }
            else
            {
                referenceDetails.Id = MappingDetailsList.FirstOrDefault().Id;
                referenceDetails.Key = MappingDetailsList.FirstOrDefault().Key;
                referenceDetails.Value = MappingDetailsList.FirstOrDefault().Value;
                ruleMappingDetails.ReferenceDetails = referenceDetails;
            }
            // 基础数据判断
            if (string.IsNullOrEmpty(Id))
            {
                // 请求后端接口 
                var res = await HttpHelper<int>.PostAsync(ApiUrl.AddRuleMapping, new ReqAddRuleMapping()
                {
                    RuleId = _ruleId,
                    Descption = Descption,
                    KeyValue = keyValue,
                    RegStr = keyValue == null ? RegStr : null,
                    Details = ruleMappingDetails
                }) ; 

                //  判断结果
                MsgUtil.ShowMsg(res.Code, "新增成功", res.ErrorMsg);
            }
            else
            {
                // 请求后端接口 
                var res = await HttpHelper<int>.PutAsync($"{ApiUrl.UpdateRuleMapping}", new ReqUpdateRuleMapping()
                {
                    Id = Id,
                    RuleId = _ruleId,
                    Descption = Descption,
                    KeyValue = keyValue,
                    RegStr = keyValue == null ? RegStr : null,
                    Details = ruleMappingDetails
                });
                // 判断结果
                MsgUtil.ShowMsg(res.Code, "修改成功", res.ErrorMsg);
            }
            this.FromClose();
        }
        #endregion


        protected override async void Query(string? type)
        {
        
             if (type == "Brand")
            {
                Page_Brand_Query brand_Query = new Page_Brand_Query();
                ((BrandQueryViewModel)brand_Query.DataContext).InformationRequested += Brand_InformationRequested;
                brand_Query.ShowDialog();
            }
          
        }

        public void SelectedTypeChange(int? type)
        {
            if (type == -1)
            {
                AddBtnVisibility = Visibility.Hidden;
                DeleteBtnVisibility = Visibility.Hidden;
                SelectBtnVisibility = Visibility.Hidden;
            }
            else if (type == 0)
            {
                AddBtnVisibility = Visibility.Visible;
                DeleteBtnVisibility = Visibility.Visible;
                SelectBtnVisibility = Visibility.Hidden;
            }
            else
            {
                AddBtnVisibility = Visibility.Hidden;
                DeleteBtnVisibility = Visibility.Hidden;
                SelectBtnVisibility = Visibility.Visible;
            }
            MappingDetailsList = new ObservableCollection<MappingDetails>();
        }

        #region 新增
        /// <summary>
        /// 新增事件
        /// </summary>
        private DelegateCommand? _addCommand;
        /// <summary>
        /// 新增事件
        /// </summary>
        public DelegateCommand AddCommand => _addCommand ?? (_addCommand = new DelegateCommand(Add));
        /// <summary>
        /// 新增
        /// </summary>
        protected  void Add(object? obj) {
            Page_RuleValueDetails_Modify view = new Page_RuleValueDetails_Modify();
            ((RuleValueDetailsModifyViewModel)view.DataContext).InformationRequested += ValueDetails_InformationRequested;
            view.ShowDialog();
        }
        private void ValueDetails_InformationRequested(object sender, InformationEventArgs<MappingDetails> e)
        {
            MappingDetailsList.Add(e.Information);
        }

        #endregion

        #region 批量删除
        /// <summary>
        /// 批量删除事件
        /// </summary>
        private DelegateCommand? _batchDeleteCommand;
        /// <summary>
        /// 批量删除事件
        /// </summary>
        public DelegateCommand BatchDeleteCommand => _batchDeleteCommand ?? (_batchDeleteCommand = new DelegateCommand(BatchDelete));
        protected  void BatchDelete(object? obj) {
            MappingDetailsList = new ObservableCollection<MappingDetails>();
            MappingDetailsList.AddRange(((ObservableCollection<MappingDetails>)obj).Where(a => a.IsSelected != true));
        }

        #endregion

        #region 选择

        private DelegateCommand? _selecCommand;

        public DelegateCommand SelectCommand => _selecCommand ?? (_selecCommand = new DelegateCommand(Select));

        protected void Select(object? obj)
        {
            if (SelectedTypeIndex == (int)MappingDetailsDisplayType.品牌)
            {
                Page_Brand_Query brand_Query = new Page_Brand_Query();
                ((BrandQueryViewModel)brand_Query.DataContext).InformationRequested += Brand_InformationRequested;
                brand_Query.ShowDialog();
            }
            else if (SelectedTypeIndex == (int)MappingDetailsDisplayType.车系)
            {
                Page_VehicleSeries_Query brand_VehicleSeries = new Page_VehicleSeries_Query();
                ((VehicleSeriesQueryViewModel)brand_VehicleSeries.DataContext).InformationRequested += VehicleSeries_InformationRequested;
                brand_VehicleSeries.ShowDialog();
            }
            else if (SelectedTypeIndex == (int)MappingDetailsDisplayType.车型)
            {
                Page_CarType_Query brand_CarType = new Page_CarType_Query();
                ((CarTypeQueryViewModel)brand_CarType.DataContext).InformationRequested += CarType_InformationRequested;
                brand_CarType.ShowDialog();
            }
            else if (SelectedTypeIndex == (int)MappingDetailsDisplayType.车型版本)
            {
                Page_CarTypeVersion_Query view = new Page_CarTypeVersion_Query();
                ((CarTypeVersionQueryViewModel)view.DataContext).InformationRequested += CarTypeVersion_InformationRequested;
                view.ShowDialog();
            }
            else if (SelectedTypeIndex == (int)MappingDetailsDisplayType.汽车配件)
            {
                Page_CarParts_Query view = new Page_CarParts_Query();
                ((CarPartsQueryViewModel)view.DataContext).InformationRequested += CarParts_InformationRequested;
                view.ShowDialog();
            }
        }

        /// <summary>
        /// 品牌
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Brand_InformationRequested(object sender, InformationEventArgs<RepBrand> e)
        {
            if (e.Information != null)
            {
                MappingDetailsList = new ObservableCollection<MappingDetails>();
                MappingDetails details = new MappingDetails();
                details.Key = "品牌";
                details.Value = e.Information.Name;
                details.Id = e.Information.Id;
                MappingDetailsList.Add(details);
            }
        }

        /// <summary>
        /// 车系
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void VehicleSeries_InformationRequested(object sender, InformationEventArgs<RepVehicleSeries> e)
        {
            if (e.Information != null)
            {
                MappingDetailsList = new ObservableCollection<MappingDetails>();
                MappingDetails details = new MappingDetails();
                details.Key = "车系";
                details.Value = e.Information.Name;
                details.Id = e.Information.Id;
                MappingDetailsList.Add(details);
            }
        }

        /// <summary>
        /// 车型
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CarType_InformationRequested(object sender, InformationEventArgs<RepCarType> e)
        {
            if (e.Information != null)
            {
                MappingDetailsList = new ObservableCollection<MappingDetails>();
                MappingDetails details = new MappingDetails();
                details.Key = "车型";
                details.Value = e.Information.Name;
                details.Id = e.Information.Id;
                MappingDetailsList.Add(details);
            }
        }

        /// <summary>
        /// 车型版本
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CarTypeVersion_InformationRequested(object sender, InformationEventArgs<RepCarTypeVersion> e)
        {
            if (e.Information != null)
            {
                MappingDetailsList = new ObservableCollection<MappingDetails>();
                MappingDetails details = new MappingDetails();
                details.Key = "车型版本";
                details.Value = e.Information.SalesName;
                details.Id = e.Information.Id;
                MappingDetailsList.Add(details);
            }
        }

        /// <summary>
        /// 配件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CarParts_InformationRequested(object sender, ListInformationEventArgs<RepCarParts> e)
        {
            if (e.Information != null)
            {
                RepCarParts repCarParts= e.Information.FirstOrDefault();
                MappingDetailsList = new ObservableCollection<MappingDetails>();
                MappingDetails details = new MappingDetails();
                details.Key = "配件";
                details.Value = repCarParts.Name;
                details.Id = repCarParts.Id;
                MappingDetailsList.Add(details);
            }
        }


        #endregion
    }
}
